package stack;
import stack.stackDefine.MyArrayListStack;

import java.util.Arrays;
import java.util.List;

/**
 * 用栈求解逆波兰表达式的值
 * 有一个bug为：正则表达式只能匹配0-9之间的数字
 *  过了一天修复了bug . \\d+
 */
public class PolandNotation {
    public static void main(String[] args) {
        polandExpression("3 4 + 5 * 6 -");
    }
    public static void polandExpression(String suffixExpression){
        String[] split = suffixExpression.split(" ");
        List<String> list = Arrays.asList(split);
        System.out.println(list);
        MyArrayListStack<String> stack = new MyArrayListStack<>();
        for (String s : list) {
            if (s.matches("\\d+")){
                stack.push(s);
            }else {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                int res = 0;
                try{
                    res = stack.cal(num1,num2,s.charAt(0));
                }catch (Exception e){
                    e.printStackTrace();
                }
                stack.push("" + res);
            }
        }
        System.out.println("value:  "+stack.pop());
    }
}
